package org.jash.learnmvp.chat;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCursorResult;

import org.jash.learnmvp.R;


public class ChatFragment extends Fragment {
    private RecyclerView recycler;
    private ConversationAdapter adapter;

    public ChatFragment() {
        super(R.layout.fragment_chat);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        recycler = view.findViewById(R.id.recycler);
        adapter = new ConversationAdapter();
        adapter.setListener(contact -> requireContext().startActivity(new Intent(requireContext(), ChatDetailActivity.class){{
            putExtra("username", contact.conversationId());
        }}));

        recycler.setAdapter(adapter);
        EMClient.getInstance().chatManager().asyncFetchConversationsFromServer(50, "", new EMValueCallBack<EMCursorResult<EMConversation>>() {
            @Override
            public void onSuccess(EMCursorResult<EMConversation> emConversationEMCursorResult) {
                requireActivity().runOnUiThread(() -> adapter.addAll(emConversationEMCursorResult.getData()));
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }
}